import router, { resetRouter } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { constantRoutes,menuRoute } from './router/constantRoutes'
import { getRoutes } from './utils/routesFromMenus'

import { getName } from '@/utils/auth'
// 顶部加载条配置
NProgress.configure({ showSpinner: false })

let isfirst=true

// 白名单设置：无需登录验证
const whiteList = ['/login']
router.beforeEach(async(to, from, next) => {
  NProgress.start()// 开启顶部加载条
  document.title = getPageTitle(to.meta.title)// 设置页面标题

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = getName('adminName')//有用户名
      const menus=store.getters.menus//有菜单
      if (hasGetUserInfo&&menus) {//已经登录
        next()
      } else {//登录或刷新页面
        try {
          if (isfirst) {
            if (from.path!=='/login'){
              if(hasGetUserInfo) store.dispatch('user/saveName',hasGetUserInfo)
            }
            isfirst = false
            await store.dispatch('menu/getMenu')
            let { menus } = store.getters
            const newRoutes =[...getRoutes(menus),menuRoute]
            resetRouter()//重置路由
            router.options.routes = [...constantRoutes, ...newRoutes]
            router.addRoutes(newRoutes)
          }
          next({ ...to, replace: true })//确保动态路由加载完再执行
          // next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else { //go login page
    /* has no token*/

    // 白名单检测：白名单页面直接跳转
    if (whiteList.indexOf(to.path) !== -1) {//login in to.path
      // in the free login whitelist, go directly
      next()
    } else {//login no in to.path
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 关闭顶部加载条
  NProgress.done()
})
